package top.kaoshanji.p3ch13a;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.FilePermission;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.GuardedObject;

/**
 * 代码清单-p3ch13a-423页b：GuardedObject类和Guard接口的使用示例
 * author kaoshanji
 * ^_^
 * create time 2025/2/8 10:36
 */
public class UseGuard {

    private static final Logger logger = LogManager.getLogger(UseGuard.class);

    public static void main(String[] args) throws IOException {
        logger.info("...代码清单-p3ch13a-423页b：GuardedObject类和Guard接口的使用示例...");

        Path path = Paths.get("myapp.conf");
        UseGuard guard = new UseGuard();
        guard.useFile(path);
    }

    public GuardedObject readFile(Path path) throws IOException {
        FilePermission permission = new FilePermission(path.toString(), "read");
        byte[] data = Files.readAllBytes(path);
        return new GuardedObject(data, permission);
    }

    public void useFile(Path path) throws IOException {
        GuardedObject guardedObj = readFile(path);
        byte[] data = (byte[]) guardedObj.getObject();
        System.out.println(data.length);
    }

}
